<template>
  <div class="express-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">跑腿服务管理系统</h1>
	            <p class="sub-title">每一条跑腿信息都承载着期待，每一次管理调度都关乎体验，用心守护服务全程，让 “帮您办” 变成 “办得好”</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="快递详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="快递信息" direction="vertical" :column="4" :model="messageForm" border>
        <el-descriptions-item label="ID" :span="2">{{ messageForm.id }}</el-descriptions-item>
        <el-descriptions-item label="快递单号" :span="2">{{ messageForm.waybillNumber }}</el-descriptions-item>
        <el-descriptions-item label="收件人" :span="2">{{ messageForm.recipientName }}</el-descriptions-item>
        <el-descriptions-item label="联系方式" :span="2">{{ messageForm.contact }}</el-descriptions-item>
        <el-descriptions-item label="收件地址" :span="2">{{ messageForm.address }}</el-descriptions-item>
        <el-descriptions-item label="成员ID" :span="2">{{ messageForm.memberId }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">
          <el-tag :type="messageForm.status === 'PENDING' ? 'warning' : 'success'">
            {{ messageForm.status === 'PENDING' ? '待取' : messageForm.status === 'COLLECTED' ? '已取' : '已送达' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ messageForm.remarks || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible1"
      title="编辑快递"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="ruleForm" 
        :rules="rules" 
        ref="ruleFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="快递单号" prop="waybillNumber">
              <el-input v-model="ruleForm.waybillNumber" readonly></el-input>
            </el-form-item>
            <el-form-item label="收件人" prop="recipientName">
              <el-input v-model="ruleForm.recipientName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="ruleForm.contact"></el-input>
            </el-form-item>
            <el-form-item label="成员ID" prop="memberId">
              <el-input v-model="ruleForm.memberId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="收件地址" prop="address">
          <el-input v-model="ruleForm.address" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="ruleForm.status" placeholder="请选择状态">
            <el-option label="待取" value="PENDING"></el-option>
            <el-option label="已取" value="COLLECTED"></el-option>
            <el-option label="已送达" value="DELIVERED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="ruleForm.remarks" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确定修改</el-button>
          <el-button @click="dialogVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog
      v-model="dialogVisible2"
      title="新增快递"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="快递单号" prop="waybillNumber">
              <el-input v-model="addForm.waybillNumber"></el-input>
            </el-form-item>
            <el-form-item label="收件人" prop="recipientName">
              <el-input v-model="addForm.recipientName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="addForm.contact"></el-input>
            </el-form-item>
            <el-form-item label="成员ID" prop="memberId">
              <el-input v-model="addForm.memberId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="收件地址" prop="address">
          <el-input v-model="addForm.address" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="待取" value="PENDING"></el-option>
            <el-option label="已取" value="COLLECTED"></el-option>
            <el-option label="已送达" value="DELIVERED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="addForm.remarks" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()">确定添加</el-button>
          <el-button @click="dialogVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 显示表界面 -->
    <el-row style="width: 100%;">
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px;">
        <el-col :span="6">
          <el-input 
            placeholder="输入快递单号查询" 
            v-model="Condition.searchQuery" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="Condition.selectedStatus" 
            placeholder="选择状态" 
            style="width: 100%;"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="待取" value="PENDING"></el-option>
            <el-option label="已取" value="COLLECTED"></el-option>
            <el-option label="已送达" value="DELIVERED"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            icon="el-icon-plus" 
            @click="openDetails2" 
            style="width: 100%;"
          >
            新增
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="info" 
            icon="el-icon-clock" 
            @click="showPendingOnly" 
            style="width: 100%;"
          >
            只看待取
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="info" 
            icon="el-icon-refresh" 
            @click="fetchTableData" 
            style="width: 100%;"
          >
            全部
          </el-button>
        </el-col>
      </el-row>
      
      <el-table 
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="waybillNumber" label="快递单号" width="180" align="center"></el-table-column>
        <el-table-column prop="recipientName" label="收件人" width="120" align="center"></el-table-column>
        <el-table-column prop="contact" label="联系方式" width="150" align="center"></el-table-column>
        <el-table-column prop="address" label="收件地址" width="250" align="center"></el-table-column>
        <el-table-column prop="memberId" label="成员ID" width="100" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'PENDING' ? 'warning' : 'success'">
              {{ scope.row.status === 'PENDING' ? '待取' : scope.row.status === 'COLLECTED' ? '已取' : '已送达' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" icon="el-icon-view" @click="openDetails(scope.row)">查看</el-button>
              <el-button type="warning" size="mini" icon="el-icon-edit" @click="openDetails1(scope.row)">编辑</el-button>
              <el-button 
                type="success" 
                size="mini" 
                icon="el-icon-check" 
                @click="markAsCollected(scope.row)"
                :disabled="scope.row.status !== 'PENDING'"
              >
                标记已取
              </el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

// 对话框控制变量
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)

// 搜索条件
const Condition = reactive({
  searchQuery: '',
  selectedStatus: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])

// 表单引用
const ruleFormRef = ref(null)
const addFormRef = ref(null)

// 详情表单数据
const messageForm = reactive({
  id: '',
  waybillNumber: '',
  recipientName: '',
  contact: '',
  address: '',
  memberId: '',
  status: '',
  remarks: ''
})

// 编辑表单数据
const ruleForm = reactive({
  id: '',
  waybillNumber: '',
  recipientName: '',
  contact: '',
  address: '',
  memberId: '',
  status: '',
  remarks: ''
})

// 新增表单数据
const addForm = reactive({
  waybillNumber: '',
  recipientName: '',
  contact: '',
  address: '',
  memberId: '',
  status: 'PENDING',
  remarks: ''
})

// 表单验证规则 - 已删除成员ID的数字验证条件
const rules = reactive({
  waybillNumber: [
    { required: true, message: '请输入快递单号', trigger: 'blur' }
  ],
  recipientName: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收件地址', trigger: 'blur' }
  ],
  memberId: [
    { required: true, message: '请输入成员ID', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 打开详情对话框
function openDetails(row) {
  dialogVisible.value = true
  Object.assign(messageForm, row)
}

// 打开编辑对话框
function openDetails1(row) {
  dialogVisible1.value = true
  // 深拷贝行数据到表单
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = row[key] ?? ''
  })
}

// 打开新增对话框
function openDetails2() {
  dialogVisible2.value = true
  // 重置表单
  Object.keys(addForm).forEach(key => {
    addForm[key] = key === 'status' ? 'PENDING' : ''
  })
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 分页大小改变
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页改变
function handleCurrentChange(val) {
  currentPage.value = val
}

// 提交编辑表单
function submitForm() {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return

    const loading = ElLoading.service({ text: '修改中...' })
    post('/express/update', ruleForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('修改成功！')
        dialogVisible1.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '修改失败')
      }
    })
  })
}

// 处理新增
function handleAdd() {
  addFormRef.value.validate((valid) => {
    if (!valid) return

    const loading = ElLoading.service({ text: '添加中...' })
    post('/express/add', addForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('添加成功！')
        dialogVisible2.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 处理删除
function handleDelete(row) {
  ElMessageBox.confirm(`确定删除快递 ${row.waybillNumber} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/express/deletebyid', { id: row.id }, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 标记为已取
function markAsCollected(row) {
  if (row.status !== 'PENDING') {
    ElMessage.warning('只有待取状态的快递可以标记为已取')
    return
  }
  
  ElMessageBox.confirm(`确定将快递 ${row.waybillNumber} 标记为已取吗？`, '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    const loading = ElLoading.service({ text: '处理中...' })
    post('/express/collect', { waybillNumber: row.waybillNumber }, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('已取')) {
        ElMessage.success('标记成功！')
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '标记失败')
      }
    })
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 只显示待取快递
function showPendingOnly() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/express/getPending', {}, (res) => {
    loading.close()
    if (res.status === 1 || Array.isArray(res)) {
      tableData.value = res.data || res
      ElMessage.success(`找到 ${tableData.value.length} 条待取快递`)
    } else {
      tableData.value = []
      ElMessage.warning('未找到待取快递')
    }
  })
}

// 搜索快递
function handleSearch() {
  // 构建搜索条件
  const params = {}
  if (Condition.searchQuery) {
    params.waybillNumber = Condition.searchQuery
  }
  if (Condition.selectedStatus) {
    params.status = Condition.selectedStatus
  }
  
  const loading = ElLoading.service({ text: '搜索中...' })
  // 如果有搜索条件，使用条件搜索，否则获取全部
  if (Object.keys(params).length > 0) {
    // 假设存在这个接口，如果不存在可以过滤本地数据
    post('/express/getByCondition', params, (res) => {
      loading.close()
      if (res.status === 1 || Array.isArray(res)) {
        tableData.value = res.data || res
        ElMessage.success(`找到 ${tableData.value.length} 条记录`)
      } else {
        tableData.value = []
        ElMessage.warning('未找到匹配记录')
      }
    })
  } else {
    fetchTableData()
    loading.close()
  }
}

// 获取所有快递数据
function fetchTableData() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/express/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1 || Array.isArray(res)) {
      tableData.value = res.data || res
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  })
}

// 页面挂载时加载数据
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.express-container {
  width: 100%;
  box-sizing: border-box;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}

.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {	
  margin-top: 20px;
}

.el-form-item .el-button {
  margin-right: 5px;
}

.el-form {
  padding: 10px;
}
</style>
